import os
import shelve
from datetime import datetime
from flask import Flask,request,render_template,redirect

app=Flask(__name__)

BASE_DIR=os.path.abspath(os.path.dirname(__file__))
DATA=os.path.join(BASE_DIR,"i.bat")

def saveFunc(name,capture_time,content):
    """
    保存数据
    :param name:
    :param capture_time:
    :param content:
    :return:
    """
    databox=shelve.open(DATA)
    if 'info_box' not in databox:
        info_box=[]
    else:
        info_box=databox['info_box']
    info_box.insert(0,{'name':name,
                       'capture_time':capture_time,
                       'content':content
                       })
    databox['info_box']=info_box
    databox.close()

def load_data():
    """
    加载保存的数据
    :return:
    """
    databox=shelve.open(DATA)
    info_box=databox.get('info_box',[])
    databox.close()
    return info_box

@app.route("/")
def index():
    info_box=load_data()
    return render_template("index.html",info_box=info_box)


@app.route("/post",methods=["POST"])
def post():
    if request.method=='POST':
        name=request.form.get('name')
        capture_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        content=request.form.get('content')
        saveFunc(name,capture_time,content)
        return redirect("/")


if __name__ == '__main__':
    app.run(host="0.0.0.0",debug=True)